package com.example.demo.controller;

import com.example.demo.common.response.ResponseResult;
import com.example.demo.service.PublicService;
import com.example.demo.util.YunOxTools;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Random;



@RestController
@RequestMapping("/public")
public class PublicController {
    @Value("${file.image.address}")
    private String imageAddress;

//    添加跨域注解
    @CrossOrigin(origins = "*", maxAge = 3600)
    @PostMapping("/uploadPic")
    public ResponseResult uploadPic(@RequestParam("file")MultipartFile file) throws IOException {
        System.out.println(file);
        if (file.isEmpty()){
            return ResponseResult.failed("文件为空");
        }

        Files.createDirectories(Paths.get(imageAddress));//读yml文件中配置的路径地址
        // 生成文件唯一性名称
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        //创建了一个唯一的文件名
        String newFilename = YunOxTools.getTime("MMddHHmmss")+YunOxTools.generateRandomCode(4);
        String fileName = newFilename + extension;
        File newFile = new File(imageAddress, fileName);
        file.transferTo(newFile);
        return ResponseResult.success("http://localhost:8090/image/"+fileName);
    }
//    照片墙上传







}
